package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.UserContext;
import com.jzo2o.customer.enums.AuditStatusEnum;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.WorkerCertificationAuditMapper;
import com.jzo2o.customer.model.domain.ServeProvider;
import com.jzo2o.customer.model.domain.WorkerCertification;
import com.jzo2o.customer.model.domain.WorkerCertificationAudit;
import com.jzo2o.customer.model.dto.request.CertificationAuditReqDTO;
import com.jzo2o.customer.model.dto.request.WorkerCertificationAuditAddReqDTO;
import com.jzo2o.customer.model.dto.request.WorkerCertificationAuditPageQueryReqDTO;
import com.jzo2o.customer.model.dto.response.WorkerCertificationAuditResDTO;
import com.jzo2o.customer.service.IServeProviderService;
import com.jzo2o.customer.service.IWorkerCertificationAuditService;
import com.jzo2o.customer.service.IWorkerCertificationService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * @Description WorkerCertificationAuditServiceImpl
 * @Author jzh
 * @Date 2025-08-07  11:02
 */

@Service
public class WorkerCertificationAuditServiceImpl extends ServiceImpl<WorkerCertificationAuditMapper, WorkerCertificationAudit> implements IWorkerCertificationAuditService {

    @Resource
    private IWorkerCertificationService workerCertificationService;

    @Resource
    private IServeProviderService serveProviderService;

    @Resource
    private WorkerCertificationAuditMapper workerCertificationAuditMapper;

    /**
     * 服务人员提交认证审核申请
     * @param workerCertificationAuditAddReqDTO
     */
    @Override
    @Transactional
    public void auditSubmit(WorkerCertificationAuditAddReqDTO workerCertificationAuditAddReqDTO) {
        // 新增认证审核记录
        WorkerCertificationAudit workerCertificationAudit = BeanUtil.toBean(workerCertificationAuditAddReqDTO, WorkerCertificationAudit.class);
        // 默认未审核
        workerCertificationAudit.setAuditStatus(AuditStatusEnum.NO.getStatus());
        save(workerCertificationAudit);

        Long serveProviderId = workerCertificationAuditAddReqDTO.getServeProviderId();
        // 同步保存到serve_provider表
        ServeProvider serveProvider = serveProviderService.getById(serveProviderId);
        serveProvider.setName(workerCertificationAuditAddReqDTO.getName());
        serveProviderService.updateById(serveProvider);

        // 查询认证记录
        WorkerCertification workerCertification = workerCertificationService.getById(serveProviderId);
        if(ObjectUtil.isNotNull(workerCertification)){
            // 将认证状态更新为认证中
            workerCertification.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
            workerCertificationService.updateById(workerCertification);
        } else {
            workerCertification = new WorkerCertification();
            workerCertification.setId(serveProviderId);
            workerCertification.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
            workerCertificationService.save(workerCertification);
        }
    }

    /**
     * 查询最新的驳回原因
     *
     * @return
     */
    @Override
    public HashMap<String, String> rejectReason() {
        Long serveProviderId = UserContext.getCurrentUser().getId();

        List<WorkerCertificationAudit> workerCertificationAuditList = lambdaQuery()
                .eq(WorkerCertificationAudit::getServeProviderId, serveProviderId)
                .eq(WorkerCertificationAudit::getAuditStatus, AuditStatusEnum.YES.getStatus())
                .orderByDesc(WorkerCertificationAudit::getCreateTime)
                .list();

        if (ObjectUtil.isNull(workerCertificationAuditList)){
            throw new ForbiddenOperationException("还未审核");
        }
        // 取workerCertificationAuditList中最新的认证记录
        WorkerCertificationAudit workerCertificationAudit = workerCertificationAuditList.get(0);
        String rejectReason = workerCertificationAudit.getRejectReason();
        HashMap<String, String> map = new HashMap<>();
        map.put("rejectReason", rejectReason);

        return map;

    }

    /**
     * 审核服务人员认证分页查询
     * @param workerCertificationAuditPageQueryReqDTO
     * @return
     */
    @Override
    public PageResult<WorkerCertificationAuditResDTO> pageQueryWorkerAudit(WorkerCertificationAuditPageQueryReqDTO workerCertificationAuditPageQueryReqDTO) {
        PageHelper.startPage(Math.toIntExact(workerCertificationAuditPageQueryReqDTO.getPageNo()), Math.toIntExact(workerCertificationAuditPageQueryReqDTO.getPageSize()));
        Page<WorkerCertificationAuditResDTO> page = workerCertificationAuditMapper.pageQueryWorkerAudit(workerCertificationAuditPageQueryReqDTO);

        PageResult<WorkerCertificationAuditResDTO> result = new PageResult<>();
        result.setTotal(page.getTotal());
        result.setPages((long) page.getPages());
        result.setList(page.getResult());

        return result;
    }

    /**
     * 审核服务人员认证
     * @param id
     * @param certificationAuditReqDTO
     */
    @Transactional
    @Override
    public void audit(Long id, CertificationAuditReqDTO certificationAuditReqDTO) {
        // 查询认证记录
        WorkerCertificationAudit workerCertificationAudit = getById(id);
        if (ObjectUtil.isNull(workerCertificationAudit)){
            throw new ForbiddenOperationException("认证记录不存在");
        }

        Integer auditStatus = workerCertificationAudit.getAuditStatus();
        if (auditStatus == AuditStatusEnum.YES.getStatus()){
            throw new ForbiddenOperationException("认证记录已审核");
        }

        workerCertificationAudit.setAuditStatus(AuditStatusEnum.YES.getStatus());
        workerCertificationAudit.setCertificationStatus(certificationAuditReqDTO.getCertificationStatus());
        workerCertificationAudit.setAuditorId(UserContext.getCurrentUser().getId());
        workerCertificationAudit.setAuditorName(UserContext.getCurrentUser().getName());
        workerCertificationAudit.setAuditTime(LocalDateTime.now());

        // 如果认证成功，同步写入认证信息worker_certification表
        if (certificationAuditReqDTO.getCertificationStatus() == CertificationStatusEnum.FAIL.getStatus()){
            // 填充拒绝原因
            String rejectReason = certificationAuditReqDTO.getRejectReason();
            workerCertificationAudit.setRejectReason(rejectReason);

            WorkerCertification workerCertification = new WorkerCertification();
            workerCertification.setCertificationStatus(CertificationStatusEnum.FAIL.getStatus());
            workerCertification.setCertificationTime(LocalDateTime.now());
            workerCertification.setId(workerCertificationAudit.getServeProviderId());
            workerCertificationService.updateById(workerCertification);
        }
        updateById(workerCertificationAudit);

        // 如果认证成功，同步写入认证信息worker_certification表
        if (certificationAuditReqDTO.getCertificationStatus() == CertificationStatusEnum.SUCCESS.getStatus()){
            WorkerCertification workerCertification = new WorkerCertification();
            workerCertification.setId(workerCertificationAudit.getServeProviderId());
            workerCertification.setName(workerCertificationAudit.getName());
            workerCertification.setIdCardNo(workerCertificationAudit.getIdCardNo());
            workerCertification.setFrontImg(workerCertificationAudit.getFrontImg());
            workerCertification.setBackImg(workerCertificationAudit.getBackImg());
            workerCertification.setCertificationMaterial(workerCertificationAudit.getCertificationMaterial());
            workerCertification.setCertificationTime(workerCertificationAudit.getAuditTime());
            workerCertification.setCertificationStatus(CertificationStatusEnum.SUCCESS.getStatus());
            workerCertificationService.updateById(workerCertification);
        }
    }

}
